﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.WebControls;
using CNKI.Graduate.Framework.Ioc;
using CNKI.Graduate.Framework.Log;

namespace CNKI.Graduate.Framework.Cache
{
    [ServiceImplementation(Name = CacheHelper.HttpRuntimeCacheKey)]
    public class HttpRuntimeCache : IEntityCache
    {
        public bool Set(string key, string entity, TimeSpan exp)
        {
            return Set<string>(key, entity, exp);
        }

        public bool Set(string key, string entity)
        {
            return Set<string>(key, entity);
        }

        public bool Set<T>(string key, T entity, TimeSpan exp) where T : class
        {
            try
            {
                System.Web.Caching.Cache objCache = HttpRuntime.Cache;
                if (objCache.Get(key) != null)
                {
                    objCache.Remove(key);
                }
                var date = DateTime.Now.Add(exp);
                objCache.Insert(key, entity, null, date, TimeSpan.Zero);
                return true;
            }
            catch (Exception ex)
            {
                LogHandle.Error(ex);
                return false;
            }

        }

        public bool Set<T>(string key, T entity) where T : class
        {
            try
            {
                System.Web.Caching.Cache objCache = HttpRuntime.Cache;
                if (objCache.Get(key) != null)
                {
                    objCache.Remove(key);
                }
                //TimeSpan.Zero，绝对过期缓存
                //objCache.Insert(key, obj, null, DateTime.MaxValue, TimeSpan.Zero);
                //滑动缓存，如果12个小时内没有人访问，则缓存过期
                objCache.Insert(key, entity, null, DateTime.MaxValue, TimeSpan.FromHours(12));
                return true;
            }
            catch (Exception ex)
            {
                LogHandle.Error(ex);
                return false;
            }

        }

        public T Get<T>(string key) where T : class
        {
            var data = (T)HttpRuntime.Cache[key];

            return data;
        }

        public string Get(string key)
        {
            var data = HttpRuntime.Cache[key];
            return data?.ToString();
        }

        public bool Remove(string key)
        {
            try
            {
                System.Web.Caching.Cache objCache = HttpRuntime.Cache;
                if (HttpRuntime.Cache.Get(key) != null)
                {
                    objCache.Remove(key);
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHandle.Error(ex);
                return false;
            }
        }
    }


}
